<!doctype html >
<html lang="{{ config('app.locale') }}">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, max-scale=1, min-scale=1,user-scalable=no">
  <meta name="_token" content="{{ csrf_token() }}"/>

  <script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/rem.js"></script>
  <link href="{{env('CDN_RESOURCE')}}/css/mobile/feedback/mobile1.css?v={{config('app.version')}}" rel="stylesheet" type="text/css">
  <script type="text/javascript" src="https://res.wx.qq.com/open/libs/weuijs/1.1.2/weui.min.js"></script>
  <link rel="stylesheet" href="https://res.wx.qq.com/open/libs/weui/1.1.2/weui.min.css">
  <script type="text/javascript">window.CDN_RESOURCE = "{{env('CDN_RESOURCE')}}"</script>
  {{--<script src="http://qzonestyle.gtimg.cn/open/qcloud/video/h5/h5connect.js"></script>--}}


  <title>久趣英语</title>

</head>
<body>

<div class="finish-class">
  <div class="complete-icon"></div>
  <div class="complete-text">太棒啦！</div>

  <div class="class-detail">
    <div id="class-detail"></div>
    <div>本次课程老师为 <span id="teacher"></span></div>
  </div>
</div>

<div class="class-feedback">

  <div class="divider">
    <div class="s-text">课程难易度</div>
    <div class="line"></div>
  </div>

  <div class="select-level">
    <div>太简单</div>
    <div>适中</div>
    <div>太困难</div>
  </div>

  <div class="rate-comment">

    <div class="divider " id="rateDivider">
      <div class="l-text">请您评价本堂课，鼓励我们做得更好</div>
      <div class="line"></div>
    </div>

    <div class="rates">
      <div class="item">
        <label>系统平台</label>
        <div class="star-rate" data-type="1" id="systemRating">
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
        </div>
      </div>

      <div class="tags" id="tags-1">
      </div>

      <div class="item">
        <label>外教授课</label>
        <div class="star-rate" data-type="2" id="teacherRating">
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
          <div class="star dis-star-icon"></div>
        </div>
      </div>

      <div class="tags" id="tags-2">
      </div>

      <div class="tip" id="tip">
        <div class="text">厉害了</div>
        <div class="arrow"></div>
      </div>
    </div>

    <div class="tags" id="tags">
    </div>

    <textarea class="comments" id="comments" placeholder="感觉本课怎么样，都还满意吗？来叨叨几句吧！"></textarea>
    <div class="submit-btn">
      提交
    </div>
    <a href="#" id="share">
      <div class="share-now-btn">分享给好友</div>
    </a>
  </div>

  <div class="clock-success">
    <div class="clock-notice">
      <img class="head" src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/msgbox-head.png">
      <div class="title">打卡成功</div>
      <div class="content">恭喜获得</div>
      <div class="ticket">
        <div class="left" id="coupon-id">5</div>
        <div class="right">
          <div class="ticket-name">打卡奖学金</div>
          <div class="ticket-time">2018/03/04</div>
        </div>
      </div>
      <div class="thank">好的</div>
    </div>
  </div>
  <div class="clock-share">
    <div class="clock-notice">
      <img class="head" src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/msgbox-head.png">
      <div class="clock-title" id="clock-info">
        <div class="title" id="clock-title">「挑战8周完成40节课任务」</div>
        <div class="day" id="clock-day">第1次</div>
      </div>
      <img class="notic-img" src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/clock-notice-3.png">
      <div class="share-btn" style="margin-top: 0.13rem;">打卡得奖学金</div>
    </div>
  </div>
  <div class="share-friend">
    <div class="clock-notice">
      <img class="head" src="{{env('CDN_RESOURCE')}}/mobile/campaign/achievement/img/msgbox-head.png">
      <div class="title">提交成功</div>
      <div class="share-btn" style="margin-top: 0.13rem;">分享给好友</div>
    </div>
  </div>
  <div class="share-mask">
    <div class="share-arrow"></div>
    {{--<div class="share-text">点击分享给好友 ^ _ ^ </div>--}}
  </div>
</div>

<div id="alertBox" class="alert-box"></div>

<script type="text/javascript" src="https://static-app.97kid.com/wx/js/zepto.min.js"></script>
<!--引入微信js-SDK-->
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/wx_config.js" crossorigin></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/Zepto_fx_methods.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/mobile/login.js?v={{config('app.version')}}" crossorigin></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/moment.min.js"></script>
<script type="text/javascript" src="{{env('CDN_RESOURCE')}}/js/AV.analytics.js"></script>


<script type="text/javascript">
  window.onerror = function(msg, url, line, col, error) {
    $.ajax({
      type: 'POST',
      url: '/wx/error',
      headers: {
        'X-CSRF-TOKEN': '{{ csrf_token() }}'
      },
      data: {
        page: 'feedback',
        msg: msg,
        url: url,
        line: line,
        col: col,
        error: error,
      }
    })
  };
  (function ($) {
    $(function () {
      var fetchedCount = 0;
      var fetchNeededCount = 1;
      var isInWechat = false
      var userAgent = navigator.userAgent
      var wechatInfo = userAgent.match(/MicroMessenger\/([\d\.]+)/i)
      if (wechatInfo) {
        isInWechat = true
      }
      var wxconfig = null
      var analytics = AV.analytics({
        appId: 'antYy9lOFi5mkU9QKjtYmRLM-gzGzoHsz',
        appKey: 'jqyWxLyobpsmdwsJddJlDheb',
        channel: isInWechat ? 'weixin' : ''
      })
      var appointmentId = '{{$appointmentId}}'
      analytics.send({
        event: 'feedback-open',
        attr: {
          appointmentId: appointmentId
        }
      })

      var configOption = {
        timestamp: '{{$signature['timestamp']}}',
        nonceStr: '{{$signature['nonceStr']}}',
        signature: '{{$signature['signature']}}',
        jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage'],
      }
      wxconfig = new WxConfig(configOption, 'feedback')

      var starCount = 5
      var rating = 0
      var teacherRating = 0
      var tags = []
      var review = ''
      var difficulty = ''
      var unFeedback = true // true 未评论  , false 已经评论 或者 获取feedback信息出错
      var achievement = null, clocks = null
      var userInfo = null
      var channel = Math.random() < 0.5 ? 'achievement_link' : 'achievement_qrcode'
      var shareFlag = ''
      var shareMsg = {
        title: '【Qkids久趣】4-12岁，在家跟北美外教学英语，新用户100元体验！',
        desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
        link: window.location.protocol + '//' + window.location.host + '/wx',
        imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png',
        success: function (target) {
          analytics.send({
            event: 'feedback-share',
            attr: {
              appointmentId: appointmentId,
              target: target
            }
          })
        }
      }
      var startips = {
        'system': ['急需改进', '需要改进', '一般', '比较好', '棒极了'],
        'teaching': ['急需改进', '需要改进', '一般', '较好', '棒极了']
      }
      $('.select-level div').click(function () {
        if (unFeedback) {
          $(this).addClass('select').siblings('div').removeClass('select')
          if ($('.rate-comment').css('display') === 'none') {
            $('.rate-comment').show()
          }
          difficulty = $(this).index() + 1
        }
      })

      $('.share-now-btn, .share-btn').click(function () {
        $('.clock-share').fadeOut()
        $('.share-friend').fadeOut()
        $('.share-mask').fadeIn()
        analytics.send({
          event: 'feedback-share-click',
          attr: {
            appointmentId: appointmentId
          }
        })
      })

      $('.share-mask').click(function () {
        $(this).fadeOut()
      })

      $('.star').click(function () {
        if (unFeedback) {
          var type = $(this).parent().attr('data-type')
          var selectStar = $(this).index() + 1

          var starTop = $(this).position().top
          var starLeft = $(this).position().left

          $('#tip').css({'top': starTop - 28, 'left': starLeft - 40}).show()

          setTimeout(function () {
            $('#tip').hide()
          }, 500)

          if (parseInt(type) === 1) {
            rating = selectStar
            $('.tip .text').text(startips.system[selectStar - 1])
          } else {
            teacherRating = selectStar
            $('.tip .text').text(startips.teaching[selectStar - 1])
          }

          for (var i = 0; i < starCount; i++) {
            if (i <= (selectStar - 1)) {

              $(this).parent().find('.star').eq(i).removeClass('dis-start-icon').addClass('star-icon')
            } else {
              $(this).parent().find('.star').eq(i).removeClass('star-icon').addClass(' dis-start-icon')
            }
          }

          $('.tag').each(function () {
            var tagId = parseInt($(this).attr('data-id'));
            var starType = $(this).attr('data-type');
            var starRange = $(this).attr('data-star').split(',');

            if (starType === type) {
              if ($.inArray(selectStar + '', starRange) !== -1) {
                $(this).show()
              } else {
                $(this).removeClass('select').hide();
                if ($.inArray(tagId, tags) !== -1) {
                  var pos = tags.indexOf(tagId);
                  if (pos > -1) {
                    tags.splice(pos, 1)
                  }
                }
              }
            }
          });

          if ($('.comments').css('display') === 'none') {
            $('.comments').css('display', 'block')
            $('.submit-btn').show()
          }
        }
      })

      $('.tag').live('touchend', function () {
        if (unFeedback) {
          var selectedTag = parseInt($(this).attr('data-id'));
          if ($.inArray(selectedTag, tags) !== -1) {
            var pos = tags.indexOf(selectedTag);
            if (pos > -1) {
              tags.splice(pos, 1)
            }

          } else {
            tags.push(selectedTag)
          }
          $(this).toggleClass('select')
        }
      })

      //提交评论
      $('.submit-btn').click(function () {
        if (unFeedback) submitFeedback()
      })

      if (appointmentId === '') {

        $.toastAlert('无效的评价页面')

      } else {

        var account = new Account();
        utils.showLoading();
        function checkLoadingStatus() {
          fetchedCount += 1;
          if (fetchNeededCount <= fetchedCount) {
            utils.hideLoading();
          }
        }

        //account.forceLogin = true;

        account.getUserInfo(function (err, result) {
          if (err) {
            unFeedback = false
            $.toastAlert(err.message)
            utils.hideLoading();
          } else {
            unFeedback = true;
            userInfo = result
            shareFlag = userInfo.shareFlag
            shareMsg.link = window.location.protocol + '//' + window.location.host + '/wx?_r=' + shareFlag

            account.ajax({
              ignoreLoading: true,
              type: 'GET',
              path: '/s/appointments/' + appointmentId,
              success: function (data) {
                fetchedCount += 1;
                getFeedbackTag()
                var lassDetail = '<span id="nickName">' + (userInfo.nickName ? userInfo.nickName : '') + '</span> 已完成 '
                switch (data.course.seriesId) {
                  case 3:
                    lassDetail += '<span id="level">PL' + data.course.level + '</span> 级别 '
                    break
                  case 4:
                    lassDetail += '测评课 '
                    break
                  case 6:
                    lassDetail += '昆虫主题课 '
                    break
                  default:
                    lassDetail += '<span id="level">L' + data.course.level + '</span> 级别 '
                }
                lassDetail += '<span id="unit">' + data.lesson.name + '</span> 课程'
                $('#class-detail').html(lassDetail)
                getTeacherInfo(data.teacherId)
              },
              error: function (err) {
                checkLoadingStatus();
                //unFeedback = false;
                $.toastAlert(err.message)
              }
            })
          }
        })

        function getFeedbackTag () {
          fetchNeededCount += 1;
          account.ajax({
            ignoreLoading: true,
            auth: 'false',
            type: 'GET',
            path: '/s/feedbackTags',
            success: function (data) {
              fetchedCount += 1;
              var tags1 = '', tags2 = '';
              var index;
              for (index in data) {
                if (data[index].type === 1) tags1 += '<div class="tag" data-id="' + data[index].id + '" data-type="' + data[index].type + '" data-star="' + data[index].displayStar + '"  >' + data[index].name + '</div>'
                else tags2 += '<div class="tag" data-id="' + data[index].id + '" data-type="' + data[index].type + '" data-star="' + data[index].displayStar + '"  >' + data[index].name + '</div>'
              }
              $('#tags-1').append(tags1);
              $('#tags-2').append(tags2);
              getFeedbackDetail()
            },
            error: function (err) {
              checkLoadingStatus();
              $.toastAlert(err.message)
            }
          })
        }

        function getFeedbackDetail () {
          fetchNeededCount += 1;
          account.ajax({
            ignoreLoading: true,
            auth: 'false',
            type: 'GET',
            path: '/s/appointments/' + appointmentId + '/feedback',
            success: function (data) {
              fetchedCount += 1;
              rating = data.rating
              teacherRating = data.teacherRating
              tags = data.tags
              review = data.review
              difficulty = data.difficulty

              $('.rate-comment').show()

              //默认选中 难度
              $('.select-level div').eq(difficulty - 1).addClass('select')

              //默认选中 系统评分
              $('#systemRating > div').eq(rating - 1).click()

              //默认选中 老师评分
              $('#teacherRating > div').eq(teacherRating - 1).click()

              //默认选中标签
              $('.tags div').each(function () {
                if ($(this).css('display') === 'block') {
                  var tagId = parseInt($(this).attr('data-id'))
                  if ($.inArray(tagId, tags) !== -1) {
                    $(this).addClass('select')
                  }
                }
              })

              // 默认填充评论框
              $('.comments').val(review).attr('disabled', 'disabled')

              //设置为已经评论
              unFeedback = false

              $('.submit-btn').hide()

              $('.share-now-btn').show()
              getAchievementInfo()
            },
            error: function (err) {
              checkLoadingStatus();
              getAchievementInfo()
            }
          })
        }

        function getTeacherInfo (teacherId) {
          if (teacherId !== 0) {
            fetchNeededCount += 1;
            account.ajax({
              ignoreLoading: true,
              type: 'GET',
              path: '/s/teachers/' + teacherId,
              success: function (data) {
                checkLoadingStatus();
                $('#teacher').text(data.nickname)
              },
              error: function (err) {
                checkLoadingStatus();
                $.toastAlert(err.message)
              }
            })

          }
        }

        // 提交评论接口
        function submitFeedback () {
          var reviewData = {
            rating: rating,
            teacherRating: teacherRating,
            tags: tags,
            review: $('.comments').val(),
            difficulty: difficulty
          }

          if (!rating) {
            $.toastAlert('请您对系统评分，鼓励我们做得更好', 2)
            return
          }
          if (!teacherRating) {
            $.toastAlert('请您对老师评分，鼓励我们做得更好', 2)
            return
          }

          account.ajax({
            auth: 'false',
            type: 'POST',
            path: '/s/appointments/' + appointmentId + '/feedback',
            data: reviewData,
            success: function (data) {
              unFeedback = false // 将评论状态设置为已评论
              $('.total').text(parseFloat(parseInt(data.scholarship) / 100))
              // 刷新打卡信息接口
              getAchievementInfo(function (isClock) {
                if (isClock) {
                  // 显示打卡弹窗
                  $('.clock-share').fadeIn()
                } else {
                  // 显示提交成功.分享好友弹窗
                  $('.share-friend').fadeIn()
                }
              })
              // 统计提交评价
              analytics.send({
                event: 'feedback-submit',
                attr: {
                  appointmentId: appointmentId
                }
              })
            },
            error: function (err) {
              $.toastAlert(err.message, 2)
            }
          })
        }

        // 获取打卡记录信息
        function getAchievementInfo (callback) {
          fetchNeededCount += 1;
          account.ajax({
            ignoreLoading: true,
            type: 'GET',
            path: '/s/achievements/appointments/' + appointmentId + '/clock?timestamp=' + moment().unix(),
            success: function (resp1) {
              fetchedCount += 1;
              fetchNeededCount += 1;
              clocks = resp1 || null
              // 获取最新任务信息
              account.ajax({
                ignoreLoading: true,
                type: 'GET',
                path: '/s/achievements/current/',
                success: function (resp2) {
                  checkLoadingStatus();
                  achievement = resp2 || null
                  setAchievementInfo()
                },
                error: function () {
                  checkLoadingStatus();
                  achievement = null
                  setAchievementInfo()
                }
              })
              if (typeof callback === 'function') callback(true)
            },
            error: function () {
              checkLoadingStatus();
              clocks = null
              achievement = null
              setAchievementInfo()
              if (typeof callback === 'function') callback(false)
            }
          })
        }

        // 根据打卡信息设置相关配置
        function setAchievementInfo () {
          if (clocks) {
            // 打卡记录存在
            if (unFeedback) { // true 未评论  , false 已评论
              // 未评论
              if (!clocks.clockIn) {
                // 未评论, 未打卡
                console.log('未评论, 未打卡')
                if (hasAchievement()) {
                  // 有设定打卡任务
                  console.log('打卡记录存在, 并且有设定任务')
                  setWithAchievement() // 有设定任务
                } else {
                  // 没有设定打卡任务
                  console.log('打卡记录存在, 但没有设定任务')
                  setWithoutAchievement() // 没有设定任务
                  // 设置分享引导图片
                  setShareArrow()
                }
                // 设置分享回调打卡
                shareMsg.success = shareClock
              } else {
                // 未评论, 已打卡
                console.log('未评论, 已打卡')
                $('.share-now-btn').text('分享给好友')
              }
            } else {
              // 已评论
              if (!clocks.clockIn) {
                // 已评论, 未打卡
                console.log('已评论, 未打卡')
                if (hasAchievement()) {
                  // 有设定打卡任务
                  console.log('打卡记录存在, 并且有设定任务')
                  setWithAchievement() // 有设定任务
                  // 设置分享引导图片
                  setShareArrow()
                } else {
                  // 没有设定打卡任务
                  console.log('打卡记录存在, 但没有设定任务')
                  setWithoutAchievement() // 没有设定任务
                }
                // 设置分享回调打卡
                shareMsg.success = shareClock
              } else {
                // 已评论, 已打卡
                console.log('已评论, 已打卡')
                $('.share-now-btn').text('分享给好友')
              }
            }
          } else {
            // 打卡记录不存在
            console.log('打卡记录不存在')
            $('.share-now-btn').text('分享给好友')
          }
          console.log(shareMsg)
          wxconfig.activeShare(shareFlag, '', shareMsg)
        }

        // 是否有打卡任务
        function hasAchievement () {
          return (achievement && achievement.status === 0) && (clocks && clocks.studentAchievementId !== 0)
        }

        // 有设定任务
        function setWithAchievement () {
          var weeks = moment(achievement.targetFinishTime * 1000).diff(moment(achievement.startTime * 1000), 'weeks')
          shareMsg = {
            title: '【Qkids久趣】' + userInfo.nickname + '正在挑战' + weeks + '周跟北美外教学习' + achievement.targetLessonCount + '节课：第' + achievement.finishedLessonCount + '次课',
            desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
            link: window.location.protocol + '//' + window.location.host + '/wx/achievement/clocks/' + clocks.clockId + '/share?_r=' + shareFlag + '&_c=' + channel,
            imgUrl: clocks.lesson.logoUri || 'https://static-app.97kid.com/site-student/public/img/share.png'
          }
          $('.clock-share .notic-img').attr('src', CDN_RESOURCE + '/mobile/campaign/achievement/img/clock-notice-3.png')
          $('.clock-success .title').text('打卡成功')
          $('.clock-share .share-btn').text('打卡得奖学金')
          $('.share-now-btn').text('打卡得奖学金')
          $('#clock-title').text('「挑战' + weeks + '周完成' + achievement.targetLessonCount + '节课任务」')
          $('#clock-day').text('第' + (achievement.clockInCount + 1) + '次')
          $('#clock-info').show()
        }

        // 没有设定任务
        function setWithoutAchievement () {
          shareMsg.success = shareClock
          $('.clock-share .notic-img').attr('src', CDN_RESOURCE + '/mobile/campaign/achievement/img/clock-notice-2.png')
          $('.clock-success .title').text('分享成功')
          $('.clock-share .share-btn').text('分享得奖学金')
          $('.share-now-btn').text('分享得奖学金')
          $('#clock-info').hide()
        }

        // 分享打卡
        function shareClock (target) {
          $('.share-mask').fadeOut()
          if (target === 'timeline') clock()
        }

        // 打卡接口
        function clock (cnt) {
          account.ajax({
            type: 'POST',
            path: '/s/achievements/clocks/' + appointmentId + "?timestamp=" + moment().unix(),
            success: function (data) {
              if (data.couponId) {
                switch (data.couponId) {
                  case 32:
                    $('#coupon-id').text('3')
                    break
                  case 33:
                    $('#coupon-id').text('5')
                    break
                  case 34:
                    $('#coupon-id').text('10')
                    break
                }
                $('.ticket-time').text(moment().add(365, 'days').format('YYYY/MM/DD'))
                $('.clock-share').fadeOut()
                $('.share-mask').fadeOut()
                $('.clock-success').fadeIn()
                $('.share-now-btn').text('分享给好友')
                if (clocks && hasAchievement()) {
                  // 统计有任务分享的打卡
                  analytics.send({
                    event: 'feedback-clock',
                    attr: {
                      appointmentId: appointmentId,
                      clockId: clocks.id
                    }
                  })
                } else if (clocks) {
                  // 统计没有任务分享的打卡
                  analytics.send({
                    event: 'feedback-share',
                    attr: {
                      appointmentId: appointmentId,
                      clockId: clocks.id
                    }
                  })
                }
              }
            },
            error: function (err) {
              if (!cnt) cnt = 0;
              if (cnt < 3 && err.code == 'unknown.error') {
                return clock(cnt + 1);
              }
              $.toastAlert(err.message, 2)
            }
          })
        }

        // 设置分享引导图片
        function setShareArrow () {
          $('.share-arrow').css('background-image', 'url(\'' + CDN_RESOURCE + '/icon/mobile/share_timeline.png\')')
          $('.share-arrow').css('background-size', '1.74rem 1.21rem')
          $('.share-arrow').css('width', '1.74rem')
          $('.share-arrow').css('height', '1.21rem')
          $('.share-arrow').css('top', '0')
          $('.share-arrow').css('right', '0.6rem')
        }

        $('.thank').off('click').on('click', function () {
          $('.clock-success').fadeOut()
          var defaultLink = shareFlag ? (window.location.protocol + '//' + window.location.host + '/wx?_r=' + shareFlag) : window.location.protocol + '//' + window.location.host + '/wx'
          location.href = typeof shareMsg.link === 'string' ? shareMsg.link : defaultLink
        })
      }
    })

  })(window.Zepto)

</script>
</body>
</html>